<?php

namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

class TransactionController extends \MLM\Model\Generic\Controller {

    
    public function indexAction() {
        $identity = $this->hasSession();
        $this->layout('layout/member');
        return new ViewModel();
    }

    public function poinAction() {
        $identity = $this->hasSession();

       // $storage = new \MLM\Model\Transaction\Storage($this->_db);
       // $member = new \MLM\Model\Transaction($storage);

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }

        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $dataAccount['account_num'], "", $dateTmp1, $dateTmp2);

        //print_r($transType); die();

        //Get Messages Notif
        $this->getMsgNotif($memberId);


        $view = new ViewModel();
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('dataSaldo', $dataSaldo);

        $this->layout('layout/member');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        return $view;
    }


    public function trackingAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $date1 = date('Ymd', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $date2 = date('Ymd');

        $dateTmp1 = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $dateTmp2 = date('Y-m-d');
        
        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }

        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $dataAccount['account_num'], "", $date1, $date2);

        $transStorage = new \MLM\Model\Transaction\Storage($this->_db);
        $transType = $transStorage->getTransType();

        //print_r($transType); die();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);


        $view = new ViewModel();

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })
        })
        ");
        
        $view->setVariable('transType', $transType);
        $view->setVariable('dateTmp1', $dateTmp1);
        $view->setVariable('dateTmp2', $dateTmp2);
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('dataSaldo', $dataSaldo);
        //$view->setTerminal(true);
        return $view;

    }


    public function bonuslistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $date1 = date('Ymd', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $date2 = date('Ymd');

        $dateTmp1 = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $dateTmp2 = date('Y-m-d');

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }

        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $dataAccount['account_num'], "", $date1, $date2);

        $transStorage = new \MLM\Model\Transaction\Storage($this->_db);
        $transType = $transStorage->getTransType("Q");

        //print_r($transType); die();

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);


        $view = new ViewModel();

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
          jQuery(function($) {
            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })
        })
        ");

        $view->setVariable('transType', $transType);
        $view->setVariable('dateTmp1', $dateTmp1);
        $view->setVariable('dateTmp2', $dateTmp2);
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('dataSaldo', $dataSaldo);
        //$view->setTerminal(true);
        return $view;

    }

    
    public function totalsaldoAction(){
        $getParams = $this->getRequest()->getQuery();

        $transType = (isset($getParams['transType'])) ? $getParams['transType'] : "";
        $accNum = (isset($getParams['accNum'])) ? $getParams['accNum'] : "";
        $mutation = (isset($getParams['mutation'])) ? $getParams['mutation'] : "";
        $date1 = (isset($getParams['date1'])) ? str_replace('-', '', $getParams['date1']) : date('Ymd', mktime(0, 0, 0, date("m")  , date("d")-7, date("Y")));
        $date2 = (isset($getParams['date2'])) ? str_replace('-', '', $getParams['date2']) : date('Ymd');

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        
        $dataSaldo = $accStorage->getTotalSaldoByPeriod($memberId, $accNum, $transType, $date1, $date2);

        if ($mutation == ""){
            $tmp = '<table cellpadding="5px">
                        <tr>
                            <td>Total Kredit</td>
                            <td>: </td>
                            <td align="right"> '.$dataSaldo['kredit'] .'</td>
                        </tr>
                        <tr>
                            <td>Total Debet</td>
                            <td>: </td>
                            <td align="right"> '.$dataSaldo['debet'] .'</td>
                        </tr>
                        <tr>
                            <td>Saldo Akhir</td>
                            <td>: </td>
                            <td align="right"> '.$dataSaldo['saldo'] .'</td>
                        </tr>
                </table>';
        }else{

                $tmp = '<table cellpadding="5px">
                    <tr>
                        <td>Total Bonus</td>
                        <td>: </td>
                        <td align="right"> '.$dataSaldo['kredit'] .'</td>
                    </tr>
                    <tr>
                        <td>Saldo Akhir</td>
                        <td>: </td>
                        <td align="right"> '.$dataSaldo['saldo'] .'</td>
                    </tr>
            </table>';

        }
            
        $view = new ViewModel();
        $view->setTerminal(true);
        $view->setVariable('data', $tmp);
        return $view;
    }


    public function topupAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();


        $data = array();

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {

            $formData = $request->getPost();

            //$bankAccNo = $formData['bank_account_no'];
            $bank = $formData['slBank'];
            $jmlTopUp = $formData['jmlTopUp'];
            $tglTransfer = $formData['tglTransfer'];
            $catatan = $formData["catatan"];

            
            $data = array_merge($data,  get_object_vars($formData));

            $errorMsg = "";
            $msg = "";
            
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert topup
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->topup($identity->member_id, $identity->member_code, $bank, $jmlTopUp, $tglTransfer, $catatan);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('topup?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
            }


            //$this->view->id = $msg;
        } 

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);
        $view->setVariable('data', $data);

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript("
         jQuery(function($) {

            $('.chosen-select').chosen();

            $('#modal-form').on('shown.bs.modal', function() {
                $(this).find('.chosen-container').each(function() {
                    $(this).find('a:first-child').css('width', '210px');
                    $(this).find('.chosen-drop').css('width', '210px');
                    $(this).find('.chosen-search input').css('width', '200px');
                });
            })

            $('.date-picker').datepicker({autoclose:true}).next().on(ace.click_event, function(){
                            $(this).prev().focus();
                    });
        })
        ");

        $script = $this->getServiceLocator()->get('viewhelpermanager')
                ->get('inlineScript');
        $script->appendScript('
          jQuery(function($) {
            $("textarea[class*=autosize]").autosize({append: "\n"});
        })
        ');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }


    public function transferAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {

            $formData = $request->getPost();

            $fromAccount = $formData['acc_num'];
            $transfer = $formData['transfer'];
            $toAccount = $formData['to_account'];
            $minSaldo = $formData["min_saldo"];
            $notes = $formData["notes"];

            $data = get_object_vars($formData);
            
            $errorMsg = "";

            //Pastikan Balance
            //$modelRek = new Application_Model_Rekening();


            $getBalance = $transAccStorage->getTotalBalance($fromAccount);

            $balance = 0;
            while($getBalance->next()){
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            //cek minimum saldo
            if ($minSaldo > $balance || $minSaldo > ($balance - $transfer)) {
                $errorMsg .= "* Minimum Saldo tidak mencukupi.<br>";
            }


            /*
             * Cek Penarikan
             */

            if ($transfer > $balance) {
                $errorMsg .= "* Jumlah transfer lebih besar daripada jumlah saldo.<br>";

            }


            /*
             * Cek Akun Tujuan
             */            
            $toAcc = $transAccStorage->getAccountDetailByAcc($toAccount);
            $x = 0;
            while($toAcc->next()){
                    $res = $toAcc->current();
                    $x++;
            }
            if ($x == 0) {
                $errorMsg .= "* Nomor Akun Tujuan tidak terdaftar.<br>";

            }

            $msg = "";
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert Withdraw
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->transfer($identity->member_id, $fromAccount, $transfer, $toAccount, $notes);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('transfer?msg='.$msg);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
                $view->setVariable('data', $data);
            }


            //$this->view->id = $msg;
        } else {

            $account = $identity->member_code;

            $getBalance = $transAccStorage->getTotalBalance($account);
            while($getBalance->next()){
                    $balance = $getBalance->current();
                    $view->setVariable('amount', $balance["amount"]);
                    $view->setVariable('amount2', $balance["amount2"]);
            }
            

            $view->setVariable('acc_num', $account);

            //Get Minimal Balance
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getMinBalance = $configStorage->getConfigByName('MIN_BALANCE');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('minbalance', $minBalance['int_value']);
            }


        }

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }

    
    public function withdrawAction() {
        
        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object   

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();
        $transAccStorage = new \MLM\Model\Member\Account\Storage($db);

        if ($request->isPost()) {            

            $formData = $request->getPost();

            $fromAccount = $formData['acc_num'];
            $tarik = $formData['tarik'];
            $bank = $formData['bank_name'];
            $minSaldo = $formData["min_saldo"];
            $biaya = $formData["biaya"];


            $errorMsg = "";

            //Pastikan Balance
            //$modelRek = new Application_Model_Rekening();
            

            $getBalance = $transAccStorage->getTotalBalance($fromAccount);
            
            $balance = 0;
            while($getBalance->next()){
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            //cek minimum saldo
            if ($minSaldo > $balance || $minSaldo > ($balance - ($tarik + $biaya))) {
                $errorMsg .= "* Minimum Saldo tidak mencukupi.<br>";
            }


            /*
             * Cek Penarikan
             */

            if (($tarik + $biaya) > $balance) {
                $errorMsg .= "* Penarikan + Biaya lebih besar daripada jumlah saldo.<br>";

            }

 
            
            $msg = "";
            if ($errorMsg == "") {

                $conn->beginTransaction();

                // Insert Withdraw
                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $dataW = $transStorage->withdraw($identity->member_id, $fromAccount, $tarik, $bank);
                while($dataW->next()){
                        $res = $dataW->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();
                    return $this->redirect()->toUrl('withdraw?msg='.$msg);
                    
                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }
            }else{

                $view->setVariable('errmsg', $errorMsg);
            }


            //$this->view->id = $msg;
        } else {

            $account = $identity->member_code;

            $getBalance = $transAccStorage->getTotalBalance($account);
            while($getBalance->next()){
                    $balance = $getBalance->current();
                    $view->setVariable('amount', $balance["amount"]);
                    $view->setVariable('amount2', $balance["amount2"]);
            }

            $getBank = $transAccStorage->getMemberAccountBank($identity->member_id);
            while($getBank->next()){
                    $bank = $getBank->current();
                    $view->setVariable('bank', $bank['bank_acc_num']);
            }

            $view->setVariable('acc_num', $account);


            //Get withdrawal Fee
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getFee = $configStorage->getConfigByName('CHARGE_WITHDRAW');
            while($getFee->next()){
                    $fee = $getFee->current();
                    $view->setVariable('biaya', $fee['int_value']);
            }

            //Get Minimal Balance
            $configStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getMinBalance = $configStorage->getConfigByName('MIN_BALANCE');
            while($getMinBalance->next()){
                    $minBalance = $getMinBalance->current();
                    $view->setVariable('minbalance', $minBalance['int_value']);
            }


            //Get Minimal WIthdraw
            $getMinWithdraw = $configStorage->getConfigByName('MIN_WITHDRAW');
            while($getMinWithdraw->next()){
                    $minWithdraw = $getMinWithdraw->current();
                    $view->setVariable('minwithdraw', $minWithdraw['int_value']);
            }

        }

        $getParams = $this->getRequest()->getQuery();
        $view->setVariable('msg', $getParams["msg"]);

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);
        
        return $view;
    }


    public function payAction() {
        $identity = $this->hasSession();

       // $storage = new \MLM\Model\Transaction\Storage($this->_db);
       // $member = new \MLM\Model\Transaction($storage);

        $memberId = $identity->member_id;
        //$profile= $storage->getMemberDetail($memberId);

        $view = new ViewModel();
        //$view->setVariable('memberProfile', $profile);
        $this->layout('layout/member');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        return $view;
    }


    public function buyAction() {
        $identity = $this->hasSession();

       // $storage = new \MLM\Model\Transaction\Storage($this->_db);
       // $member = new \MLM\Model\Transaction($storage);

        $memberId = $identity->member_id;
        //$profile= $storage->getMemberDetail($memberId);

        $view = new ViewModel();
        //$view->setVariable('memberProfile', $profile);
        $this->layout('layout/member');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        return $view;
    }


    public function rewardlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }


        $memberStorage = new \MLM\Model\Member\Storage($this->_db);
        $getNumMitra = $memberStorage->getNumMitra($identity->member_id);
        $numMitra = 0;
        while($getNumMitra->next()){
                $res = $getNumMitra->current();
                $numMitra = $res['total'];
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);
        
        $view = new ViewModel();

   
        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('numMitra', $numMitra);

        //$view->setTerminal(true);
        return $view;

    }


    public function claimrewardAction() {

        $identity = $this->hasSession();

        $this->layout('layout/member');
        $view = new ViewModel();
        // init data and instance object

        $request = $this->getRequest();

        $db = $this->_db;
        $conn = $db->getDriver()->getConnection();  

        if ($request->isPost()) {

            $formData = $request->getPost();
            $bonusRewardId = $formData['bonusRewardId'];
            $rewardId = $formData['rewardId'];
            
            $conn->beginTransaction();

            // Insert Withdraw
            $transStorage = new \MLM\Model\Transaction\Storage($db);
            $dataW = $transStorage->claimReward($identity->member_id, $identity->member_code, $bonusRewardId, $rewardId);
            while($dataW->next()){
                    $res = $dataW->current();
                    $msg = $res["out_msg"];
                    $code = $res['out_code'];
            }

            if ($code == '0') {
                $conn->commit();
                $view->setVariable('msg', $msg);
                

            } else {
                $conn->rollback();
                $view->setVariable('errmsg', $msg);
            }
            
        } 

        $getParams = $this->getRequest()->getQuery();        
        $view->setTerminal(true);
        return $view;
    }
    

    public function rewardsnlistAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/member');

        $memberId = $identity->member_id;

        $accStorage = new \MLM\Model\Member\Account\Storage($this->_db);
        $getAccount = $accStorage->getAccountDetail($memberId);

        $dataAccount = array();
        while ($getAccount->next()) {
                $account = $getAccount->current();
                $dataAccount['account_num'] = $account['account_num'];
                $dataAccount['account_name'] = $account['account_name'];
        }



        $numSN = 0;
        $snStorage = new \MLM\Model\Sn\Storage($this->_db);
        $getNumSN = $snStorage->getNumSNMitra($identity->member_id);
        while($getNumSN->next()){
                $res = $getNumSN->current();
                $numSN = $res['total'];
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        $view = new ViewModel();


        $view->setVariable('dataAccount', $dataAccount);
        $view->setVariable('numSN', $numSN);

        //$view->setTerminal(true);
        return $view;

    }


    public function buysnmemberAction() {
            $identity = $this->hasSession();
            $this->layout('layout/member');
            $view = new ViewModel();

            $script = $this->getServiceLocator()->get('viewhelpermanager')
                            ->get('inlineScript');
                    $script->appendScript("
                       jQuery(function($) {

                    $('[data-rel=tooltip]').tooltip();

                    $('.select').css('width','150px').select2({allowClear:true})
                    .on('change', function(){
                            $(this).closest('form').validate().element($(this));
                    });


                    var validation = false;
                    $('#fuelux-wizard').ace_wizard().on('change' , function(e, info){
                            
                            if(info.step == 1 && validation) {
                                    if(!$('#validation-form').valid()) return false;                                    
                            }
                            if(info.step == 1) {
                                return cekTotal();
                            }
                            if(info.step == 2) {
                                return konfirmasiPembelian();
                            }
                    }).on('finished', function(e) {
                            $('#inputForm').submit();
                            $('#btnFinish').attr('disabled','disabled');

                            /*
                            bootbox.dialog('Thank you! Your information was successfully saved!', [{
                                    'label' : 'OK',
                                    'class' : 'btn-small btn-primary',
                                    }]
                            );
                            */
                    }).on('stepclick', function(e, info){

                            //return false;//prevent clicking on steps

                    });


                    $('#accordion-style').on('click', function(ev){
                            var target = $('input', ev.target);
                            var which = parseInt(target.val());
                            if(which == 2) $('#accordion').addClass('accordion-style2');
                             else $('#accordion').removeClass('accordion-style2');
                    });
                    //documentation : http://docs.jquery.com/Plugins/Validation/validate


                    $('.chosen-select').chosen();

                    $('#modal-form').on('shown.bs.modal', function() {
                        $(this).find('.chosen-container').each(function() {
                            $(this).find('a:first-child').css('width', '210px');
                            $(this).find('.chosen-drop').css('width', '210px');
                            $(this).find('.chosen-search input').css('width', '200px');
                        });
                    });


             });

            $('#qty').ace_spinner({value:0,min:1,max:9999999,step:5, btn_up_class:'btn-info' , btn_down_class:'btn-info'})
                .on('change', function(){
                        //alert(this.value)
                        //setTotalHarga(this.value);
                        return cekStok(this.value);
                });
                    ");

            $request = $this->getRequest();

            $db = $this->_db;
            $conn = $db->getDriver()->getConnection();

            if ($request->isPost()) {
                $conn->beginTransaction();
                $post = $request->getPost();

                $memberId = $identity->member_id;
                $agens = explode("-", $post['slAgen']);
                $agen = $agens[0];
                $qty   = $post['qty'];
                $price = $post['price'];
                $totalPrice = $post['totalPrice'];
                $caraBayar   = $post['rdPembayaran'];


                $transStorage = new \MLM\Model\Transaction\Storage($db);
                $trans = $transStorage->buySNMember($memberId, $identity->member_code, $agen, $price, $qty, $totalPrice, $caraBayar);
                while($trans->next()){
                        $res = $trans->current();
                        $msg = $res["out_msg"];
                        $code = $res['out_code'];
                }

                if ($code == '0') {
                    $conn->commit();

                    //Jika cash atau transfer
                    $tmp = ($caraBayar == 1 || $caraBayar == 3) ? ", silahkan lakukan konfirmasi pembayaran setelah anda membayar" : "";

                    return $this->redirect()->toUrl('buysnmember?msg='.$msg.$tmp);

                } else {
                    $conn->rollback();
                    $view->setVariable('errmsg', $msg);
                }

            }


            $storage = new \MLM\Model\Agent\Storage($db);
            $agents = $storage->getAgentList("");
            $view->setVariable('agents', $agents);


            $confStorage = new \MLM\Model\Sysconfig\Storage($db);
            $getSNPrice = $confStorage->getConfigByName('SN_PRICE');
            while ($getSNPrice->next()) {
                $res = $getSNPrice->current();
                $snPrice = $res["int_value"];
            }
            $view->setVariable('snPrice', $snPrice);

            $accStorage = new \MLM\Model\Member\Account\Storage($db);
            $accountsPT = $accStorage->getAccountBank(100);

            $getBalance = $accStorage->getTotalBalance($identity->member_code);
            while ($getBalance->next()) {
                $res = $getBalance->current();
                $balance = $res["amount"];
            }

            $getParams = $this->getRequest()->getQuery();
            $msg = (isset($getParams["msg"])) ? $getParams["msg"] : "";

            $view->setVariable('accountsPT', $accountsPT);
            $view->setVariable('balance', $balance);
            $view->setVariable('msg', $msg);

            //Get Messages Notif
            $this->getMsgNotif($identity->member_type_id, $identity->member_id);
            return $view;
     }



    //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){


        $identity = $this->hasSession();

        /*
        if ($memberId == 100) $memberId2 = $memberId;
        else{

            //$memberId2 = ($identity->member_reff_id == "") ? $memberId : $identity->member_reff_id;
            $memberId2 = $memberId;
            $isAgent = $identity->member_reff_id;
        }
         *
         */

        $isAgent = $identity->member_reff_id;
        $memberCode = $identity->member_code;


        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);

        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId, $isAgent, $memberCode);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId, $isAgent, $memberCode);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }

    
    private function hasSession() {
        $auth = new AuthenticationService();

        //$identity = $auth->getIdentity();

        if (!$auth->hasIdentity()) {
            return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
        } else {
            return $auth->getIdentity();
        }
    }

}
